<template>
  <div>
    <div class="search-container">
      <el-input
        v-model="monitorName"
        placeholder="名称"
        style="width: 10%; margin-right: 20px; margin-left: 20px; "
        class="rounded-input"
      />
      <el-input
        v-model="monitorAddress"
        placeholder="地址"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      />
      <el-select
        v-model="monitorCondition"
        placeholder="监测情况"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      >
        <el-option label="正常" value="0"></el-option>
        <el-option label="虫害较少" value="1"></el-option>
        <el-option label="虫害严重" value="2"></el-option>
        <el-option label="暂无" value="3"></el-option>
      </el-select>
      <el-button
        type="text"
        icon="el-icon-search"
        @click="fetchData"
        style="margin-left: 0;"
      ></el-button>
      <el-button
        type="text"
        icon="el-icon-refresh"
        @click="resetSearch"
        style="margin-left: 10px;"
      ></el-button>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAddMonitor"
        style="margin-left: 600px;"
      >
        添加数据
      </el-button>
      </div>
    <el-table :data="paginatedData" style="width: 100%">
      <el-table-column prop="rowId" label="ID" width="100"></el-table-column>
      <el-table-column prop="monitorImage" label="记录" width="180">
        <template slot-scope="scope">
          <div class="image-container">
            <img :src="scope.row.monitorImage" alt="记录" class="record-image" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="monitorName" label="名称" width="180"></el-table-column>
      <el-table-column prop="monitorAddress" label="地址" width="180"></el-table-column>
      <el-table-column prop="monitorCondition" label="监测情况" width="180"></el-table-column>
      <el-table-column prop="monitorType" label="监测方式" width="180"></el-table-column>
      <el-table-column prop="monitorIntroduce" label="症状" width="180"></el-table-column>
      <el-table-column prop="createdBy" label="创建人" width="150"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
    title="添加监测数据"
    :visible.sync="dialogVisible"
    width="50%"
    :before-close="handleClose"
  >
    <el-form :model="form" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="记录图片">
            <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :http-request="deviceUpload"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="form.monitorImage" :src="form.monitorImage" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="名称">
            <el-select v-model="form.monitorName" placeholder="请选择名称">
              <el-option
                v-for="item in nameOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="form.monitorAddress" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="监测情况">
            <el-select v-model="form.monitorCondition" placeholder="请选择监测情况" style="width: 75%;">
              <el-option label="正常" value="0"></el-option>
              <el-option label="虫害较少" value="1"></el-option>
              <el-option label="虫害严重" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="监测方式">
            <el-select v-model="form.monitorType" disabled style="width: 75%;">
              <el-option label="无人机监测" value="无人机监测"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="症状">
        <el-input type="textarea" v-model="form.monitorIntroduce" rows="5"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import { selectPageDevice, selectAllName, addDeviceData, deleteById, upload } from '@/api/monitor';

export default {
  name: 'Device',
  data() {
    return {
      tableData: [], // 假设这是从API获取的数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      monitorName: '',
      monitorAddress: '',
      monitorCondition: null,
      dialogVisible: false,
      form: {
        id: '',
        monitorImage: '',
        monitorName: '',
        monitorAddress: '',
        monitorCondition: '',
        monitorType: '无人机监测',
        monitorIntroduce: ''
      },
      nameOptions: [],
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end).map((row,index) => ({
        ...row,
        rowId: start + index + 1
      }))
    },
  },
  created() {
    this.fetchData();
    this.fetchNameOptions();
  },
  watch: {
    'form.monitorName': function(newVal) {
      const selectedOption = this.nameOptions.find(option => option.value === newVal);
      if (selectedOption) {
        // 假设每个选项对象中包含 address 字段
        this.form.monitorAddress = selectedOption.address;
        this.form.id = selectedOption.value;
      } else {
        this.form.monitorAddress = '';
        this.form.id = '';
      }
    }
  },
  methods: {
    fetchData() {
      const params ={
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        monitorName: this.monitorName,
        monitorAddress: this.monitorAddress,
        monitorCondition: this.monitorCondition,
      };

      // 这是一个获取数据的API调用
      selectPageDevice(params)
        .then(response => {
          this.tableData = response.data.result;
          this.total = response.data.total;
        })
        .catch(error => {
          console.error('获取数据失败', error);
        });
    },
    fetchNameOptions() {
      selectAllName()
        .then(response => {
          this.nameOptions = response.data.map(item => ({
            value: item.id,
            label: item.name,
            address: item.address
          }));
        })
        .catch(error => {
          console.error('获取名称选项失败', error);
        });
    },
    
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    resetSearch() {
      // 清空搜索框中的所有输入并恢复默认选项
      this.monitorName = null,
      this.monitorAddress = null;
      this.monitorCondition = null,
      this.fetchData(); // 重新获取数据
    },

    handleAddMonitor(){
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
      this.form = {
        id: '',
        monitorImage: '',
        monitorName: '',
        monitorAddress: '',
        monitorCondition: '',
        monitorType: '无人机监测',
        monitorIntroduce: ''
      }
    },
    handleDelete(index, row) {
      // 实现删除逻辑
      console.log('删除', index, row);
      this.$confirm('此操作将永久删除该措施, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实现删除逻辑
        console.log('删除', index, row);
        deleteById(row.id).then(response => {
          console.log(response)
          console.log('删除成功', response);
          if(response.code === 200){
            this.$message({
              message: "删除成功!",
              type: 'success'
            });
          }else{
            this.$message({
              message: response.message,
              type: 'error'
            });
          }
          this.fetchData(); // 重新获取数据
        }).catch(error => {
          console.error('删除失败', error);
        });
      }).catch(() => {
         // 用户点击取消
        this.$message({
          message: '已取消删除~',
          type: 'info'
        });
      })
    }, 
    submitForm() {
      if (!this.form.monitorCondition) {
        this.$message.error('监测情况不能为空');
        return;
      }
      if (!this.form.id) {
        this.$message.error('ID 不能为空');
        return;
      }
      console.log(this.form.monitorName)
      // 根据 form.monitorName 的 id 找到对应的名称
      const selectedOption = this.nameOptions.find(option => option.value === this.form.monitorName);
      if (selectedOption) {
        this.form.monitorName = selectedOption.label;
      } else {
        this.$message.error('无法找到对应的名称');
        return;
      }
      // 处理提交逻辑
      const param = {
        id: this.form.id,
        monitorImage: this.form.monitorImage,
        monitorName: this.form.monitorName,
        monitorCondition: this.form.monitorCondition,
        monitorIntroduce: this.form.monitorIntroduce
      }
      console.log('提交数据', param);
      // 你可以在这里调用API提交数据
      addDeviceData(param).then(response => {
        console.log('上传成功', response);
        if(response.code == 200){
          this.$message({
            message: '添加成功！',
            type: 'success'
          });
        }else{
          this.$message({
            message: response.data,
            type: 'error'
          });
        }
        this.dialogVisibleUpdate = false; // 关闭对话框
        this.handleClose();
        this.fetchData(); // 重新获取数据
      }).catch(error => {
        console.error('添加失败', error);
      });
    },
    handleAvatarSuccess(res, file) {
      this.form.pestImage = URL.createObjectURL(file.raw);
    },

    deviceUpload(options) {
      const { file } = options;
      const bucket = 'pest-control';             // 固定 bucket
      const objectName = 'image';                // 固定目录名

      upload(file, bucket, objectName)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.form.monitorImage = response.data; // 接收返回的 URL
            this.$message.success('上传成功');
          } else {
            this.$message.error('上传失败：' + (response.message || '未知错误'));
          }
        })
        .catch(() => {
          this.$message.error('请求出错，请重试');
        });
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
  border: 2px solid #d9d9d9; /* 添加外边框 */
  border-radius: 6px; /* 可选：添加圆角 */
}

.search-container {
  margin-bottom: 20px;
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.rounded-input .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}


.rounded-input:last-child .el-input__inner {
  border-radius: 20px;
  margin-right: 10px;
}

.el-select .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}

.el-button--text {
  padding: 0; /* 去掉按钮的内边距 */
  margin-left: 10px; /* 调整按钮的左边距 */
  font-size: 20px;
}

.monitor-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh; /* 确保容器至少占满整个视口高度 */
  padding: 20px;
  box-sizing: border-box;
}

.monitor-table {
  width: 100%;
  flex: 1; /* 使表格内容占据剩余空间 */
  margin-bottom: 20px;
}

.record-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.pagination-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff; /* 确保背景颜色与页面一致 */
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  padding: 10px;
  box-sizing: border-box;
}

.el-table {
  margin-bottom: 60px; /* 根据分页组件的高度调整这个值 */
}
</style>